package cn.walls1717.juc.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 售票测试ReentrantLock
 *
 * @author walls1717
 * @since 2022/12/09 22:35
 **/
@Slf4j
public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}

@Slf4j
class Ticket {
    private int num = 50;
    /*
     构造方法不加true默认为非公平锁，加了true就是公平锁。
     为什么默认是非公平锁？
       因为可以避免线程切换的开销，充分利用cpu时间片，提高性能。
     */
    ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (num > 0) {
                log.info(Thread.currentThread().getName() + "售货员，卖出第" + (num--) + "张票，" + "还剩" + num + "张票");
            }
        } finally {
            lock.unlock();
        }
    }
}
